
#include "main.h"
#include "adc.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"
#include "BC26103.h"
#include "Network communication.h"
#ifdef __GNUC__
  #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
  #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif
PUTCHAR_PROTOTYPE
{
  HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, 0xFFFF);
  return ch;
}
unsigned char UART1_Rx_Buf[MAX_REC_LENGTH] = {0};
unsigned int  UART1_Rx_cnt = 0;
unsigned char UART1_temp[REC_LENGTH] = {0};
uint8_t Read_Config_Data[4];
uint32_t timer_cnt;
uint32_t Period = 3600;
uint32_t Reset_Period = 172800;
float Gas_Value_high_th=1.5;
float Gas_Value_low_th=1.4;
uint8_t Alarm_Status = 0;
uint8_t reboot_Status = 0;
uint8_t key_down = 0;
measure_value MeasureData={0,0};
uint8_t BC26_ICCID[ICCID_Len+1];
uint8_t BC26_IMEI[IMEI_Len+1]={0};
static int8_t SocketId=-1;
uint8_t RcvFromNB_Valid_Data[4];
uint8_t Operators=0;
void Read_Config(void)
{
	uint32_t addr = 0x08008000;
	uint32_t readFlashData;
	uint8_t i;
	uint16_t read_th_data;
	uint8_t read_period;
	printf("read config data begin\r\n");
	HAL_FLASH_Unlock();
	readFlashData = *(__IO uint32_t*)addr;
	Read_Config_Data[3] = readFlashData;
	Read_Config_Data[2] = readFlashData>>8;
	Read_Config_Data[1] = readFlashData>>16;
	Read_Config_Data[0] = readFlashData>>24;
	HAL_FLASH_Lock();
	if(Read_Config_Data[0]==0x01)
	{
		read_th_data = ((uint16_t)(Read_Config_Data[2]<<8)) + ((uint16_t)(Read_Config_Data[3]));
		printf("high th is %d\r\n",read_th_data);
		Gas_Value_high_th = ((float)(read_th_data))/1000.0;
		Gas_Value_low_th = Gas_Value_high_th - 0.1;
		printf("high th is %f\r\n",Gas_Value_high_th);
		read_period = Read_Config_Data[1];
		Period = (uint32_t)( (read_period<<9) + (read_period<<6) + (read_period<<4) + (read_period<<3));
		printf("config period is %d\r\n",Period);
	}
	else
	{
		Gas_Value_high_th = 1.5;
		Gas_Value_low_th = Gas_Value_high_th - 0.1;
		Period = 3600;
		printf("high th is %f\r\n",Gas_Value_high_th);
		printf("config period is %d\r\n",Period);
	}
	printf("read config data end\r\n");
}
void Write_Config(void)
{
	uint32_t PageError = 0;
	uint32_t writeFlashData;
	uint32_t addr = 0x08008000;
	uint8_t i = 0;
	printf("write config data to flash begin\r\n");
	HAL_FLASH_Unlock();
	if (HAL_FLASHEx_Erase(&EraseInitStruct,&PageError) == HAL_OK)
	{
		printf("Erase page success\r\n");
	}
	writeFlashData = (uint32_t)(RcvFromNB_Valid_Data[(i<<2)+0]<<24) + (uint32_t)(RcvFromNB_Valid_Data[(i<<2)+1]<<16) + (uint32_t)(RcvFromNB_Valid_Data[(i<<2)+2]<<8) + (uint32_t)(RcvFromNB_Valid_Data[(i<<2)+3]);
	HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD,addr, writeFlashData);
	HAL_FLASH_Lock();
	printf("write config data to flash end\r\n");
}
void SystemClock_Config(void);
#define VERSION "v1.001"
int main(void)
{
	uint8_t 	Result=FALSE;
	float 		GAS_Val;
	timer_cnt = 0;
	reboot_Status = 1;
  HAL_Init();
  SystemClock_Config();
  MX_GPIO_Init();
  MX_ADC_Init();
  MX_TIM3_Init();
  MX_TIM6_Init();
  MX_USART1_UART_Init();
  MX_USART2_UART_Init();
	NB_PW_OFF;
	HAL_Delay(500);
	NB_PW_ON;
	printf("NB-IoT GAS-Detect version: %s\r\n",VERSION);
	HAL_UART_Receive_IT(&huart1,(uint8_t *)UART1_temp,REC_LENGTH);
	HAL_TIM_Base_Start_IT(&htim6);
	Read_Config();
	LED1_OFF;
	Time3_ch1_on();
	HAL_Delay(200);
	Time3_ch1_off();
	BC26_PowerStart();
	SocketId = BC26_IntialAndCreatSocket();
	GAS_Val = Get_GAS_Value();
	HAL_Delay(20);
	GAS_Val = Get_GAS_Value();
	if(GAS_Val>=Gas_Value_high_th)
		MeasureData.AlarmFlag=1;
	else
		MeasureData.AlarmFlag=0;
	if(SocketId<0)
		SocketId = BC26_IntialAndCreatSocket();
	if(SocketId>=0)
	{
		MeasureData.SignalStrength = BC26_Check_CESQ();
		if(Operators==1)
		{
			Result=SendMessageToServer_Mobile(SocketId,&MeasureData);
			ReceiveMessageFromServer_Mobile(SocketId);
		}
		else if(Operators==3)
		{
			Result=SendMessageToServer_Telecom(&MeasureData);
			ReceiveMessageFromServer_Telecom();
		}
	}
	reboot_Status = 0;
	LED0_ON;
	while(1)
	{
			GAS_Val = Get_GAS_Value();
			if( (GAS_Val >= Gas_Value_high_th) && (Alarm_Status==0))
			{
					printf("检测燃气泄漏\r\n");
					LED0_OFF;
					Alarm_Status = 1;
					MeasureData.AlarmFlag=1;
					if(SocketId<0)
							SocketId = BC26_IntialAndCreatSocket();
					MeasureData.SignalStrength = BC26_Check_CESQ();
					if(Operators==1)
					{
							Result=SendMessageToServer_Mobile(SocketId,&MeasureData);
							ReceiveMessageFromServer_Mobile(SocketId);
							if(Result==FALSE)
							{
									SocketId=-1;
									SocketId=BC26_IntialAndCreatSocket();
									if(SocketId>0)
									{
											Result=SendMessageToServer_Mobile(SocketId,&MeasureData);
											ReceiveMessageFromServer_Mobile(SocketId);
									}
							}
					}
					else if(Operators==3)
					{
							Result=SendMessageToServer_Telecom(&MeasureData);
							if(Result==FALSE)
							{
								SocketId=BC26_IntialAndCreatSocket();
								MeasureData.SignalStrength=BC26_Check_CESQ();
								SendMessageToServer_Telecom(&MeasureData);
							}
							ReceiveMessageFromServer_Telecom();
					}
			}
			else if( (GAS_Val <= Gas_Value_low_th) && (Alarm_Status==1) )
			{
				printf("检测燃气浓度正常\r\n");
				Time3_ch1_off();
				LED0_ON;
				LED1_OFF;
				Alarm_Status = 0;
				MeasureData.AlarmFlag=2;
				if(SocketId<0)
							SocketId = BC26_IntialAndCreatSocket();
				MeasureData.SignalStrength = BC26_Check_CESQ();
				if(Operators==1)
					{
							Result=SendMessageToServer_Mobile(SocketId,&MeasureData);
							ReceiveMessageFromServer_Mobile(SocketId);
							if(Result==FALSE)
							{
									SocketId=-1;
									SocketId=BC26_IntialAndCreatSocket();
									if(SocketId>0)
									{
											Result=SendMessageToServer_Mobile(SocketId,&MeasureData);
											ReceiveMessageFromServer_Mobile(SocketId);
									}
							}
					}
				else if(Operators==3)
				{
						Result=SendMessageToServer_Telecom(&MeasureData);
						if(Result==FALSE)
								{
									SocketId=BC26_IntialAndCreatSocket();
									if(SocketId<0)
											SocketId = BC26_IntialAndCreatSocket();
									MeasureData.SignalStrength=BC26_Check_CESQ();
									SendMessageToServer_Telecom(&MeasureData);
								}
						ReceiveMessageFromServer_Telecom();
				}
			}
		else if((timer_cnt%(Period<<1))==0)
		{
			printf("周期上传\r\n");
			Time3_ch1_off();
			LED0_ON;
			LED1_OFF;
			Alarm_Status = 0;
			if(SocketId<0)
							SocketId = BC26_IntialAndCreatSocket();
			MeasureData.AlarmFlag=3;
			MeasureData.SignalStrength = BC26_Check_CESQ();
			if(Operators==1)
					{
							Result=SendMessageToServer_Mobile(SocketId,&MeasureData);
							ReceiveMessageFromServer_Mobile(SocketId);
							if(Result==FALSE)
							{
									SocketId=-1;
									SocketId=BC26_IntialAndCreatSocket();
									if(SocketId>0)
									{
											Result=SendMessageToServer_Mobile(SocketId,&MeasureData);
											ReceiveMessageFromServer_Mobile(SocketId);
									}
							}
					}
				else if(Operators==3)
				{
						Result=SendMessageToServer_Telecom(&MeasureData);
						if(Result==FALSE)
								{
									SocketId=BC26_IntialAndCreatSocket();
									MeasureData.SignalStrength=BC26_Check_CESQ();
									SendMessageToServer_Telecom(&MeasureData);
								}
						ReceiveMessageFromServer_Telecom();
				}
		}
		else if(key_down==1)
		{
			printf("按键自检\r\n");
			key_down = 0;
			Time3_ch1_on();
			HAL_Delay(100);
			Time3_ch1_off();
			Alarm_Status = 0;
			MeasureData.AlarmFlag=4;
			if(SocketId<0)
							SocketId = BC26_IntialAndCreatSocket();
			MeasureData.SignalStrength = BC26_Check_CESQ();
			if(Operators==1)
					{
							Result=SendMessageToServer_Mobile(SocketId,&MeasureData);
							ReceiveMessageFromServer_Mobile(SocketId);
							if(Result==FALSE)
							{
									SocketId=-1;
									SocketId=BC26_IntialAndCreatSocket();
									if(SocketId>0)
									{
											Result=SendMessageToServer_Mobile(SocketId,&MeasureData);
											ReceiveMessageFromServer_Mobile(SocketId);
									}
							}
					}
				else if(Operators==3)
				{
						Result=SendMessageToServer_Telecom(&MeasureData);
						if(Result==FALSE)
								{
									SocketId=BC26_IntialAndCreatSocket();
									MeasureData.SignalStrength=BC26_Check_CESQ();
									SendMessageToServer_Telecom(&MeasureData);
								}
						ReceiveMessageFromServer_Telecom();
				}
			key_down = 0;
		}
		else
		{
			key_down = 0;
			;
		}
		HAL_Delay(100);
		if((timer_cnt%(Reset_Period<<1))==0)
		{
			timer_cnt = 0;
			HAL_NVIC_SystemReset();
		}
	}
  while (1)
  {
  }
}
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI14|RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSI14State = RCC_HSI14_ON;
  RCC_OscInitStruct.HSI14CalibrationValue = 16;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL6;
  RCC_OscInitStruct.PLL.PREDIV = RCC_PREDIV_DIV1;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1;
  PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK1;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}
void Error_Handler(void)
{
}
#ifdef  USE_FULL_ASSERT
void assert_failed(uint8_t *file, uint32_t line)
{
}
#endif